﻿#include "ecgtestdialog.h"
#include "ui_ecgtestdialog.h"
#include "userdata.h"
#include <QFile>
#include <QDebug>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QColor>
#include <QPainter>
#include <QPoint>
#include <QVector>
#include<QPointF>
#include <QFont>
#define DOTS 5

ECGTestDialog::ECGTestDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::ECGTestDialog)
{
    UserData user;
    user.setName(QStringLiteral("张怡然"));
    user.setAge(25);
    ui->setupUi(this);
    setWindowFlags(Qt::FramelessWindowHint);
    setWindowTitle(QStringLiteral("心电图"));

    ui->namelabel->setText(QStringLiteral("姓名：")+user.getName());
    ui->agelabel->setText(QString(QStringLiteral("年龄：%1")).arg(user.getAge()));

    QString fileName=":/new/prefix1/hisdata/hisdata.txt";
    m_serialflag=false;
    ReadECGFile(fileName);
     getHistoryData();
     serialPortInit();

//     if (m_channelData.isEmpty()) {
//             qDebug() << "警告：心电图数据为空！";
//         }
//    qDebug()<<m_channelData[0]->getChannelName();
//    qDebug()<<m_channelData[0]->getDataArr();/*
//    qDebug()<<m_channelData[11]->getChannelName();
//    qDebug()<<m_channelData[11]->getDataArr();*/
}

ECGTestDialog::~ECGTestDialog()
{
    for (int i = 0; i < 12; ++i) {
            delete m_channelData[i];
            m_channelData[i] = nullptr;
        }
    delete ui;
}



void ECGTestDialog::paintEvent(QPaintEvent *){
    int w=this->width();
    int h=this->height();
    int channelnum=sizeof (m_channelData)/sizeof(HeartData *);
    QPainter painter(this);
    drawHisECGWave(painter,w,h,DOTS);
    if(m_serialflag)
    {
        updateECGWave(painter,w,h,DOTS);
    }
    painter.save();
    QFont f("微软雅黑");
    //f.setBold(true);
    painter.setFont(f);
    painter.setPen(QColor(0,102,227));
    QString text=QString("Channel:%1   Speed:25mm/s").arg(channelnum);
    painter.drawText(10,20,text);
    painter.restore();

}
 void ECGTestDialog::ReadECGFile(QString fileName){
    QFile f(fileName);
    if(!f.open(QIODevice::ReadOnly|QIODevice::Text)){
        return;
    }
    QByteArray content =f.readAll();
    m_dataArrs =QJsonDocument::fromJson(content).array();
}

 void ECGTestDialog::getHistoryData(){
     int cols=2,rows=6;
     for(int col=0;col<cols;col++){
         for(int row=0;row<rows;row++){
             HeartData *tmpHeartData =new HeartData();
             QJsonObject edata =m_dataArrs.at(col*rows+row).toObject();
             QString channelName=edata["channel"].toString();
             QJsonArray dataArr=edata["value"].toArray();

             tmpHeartData->setChannelName(channelName);
             tmpHeartData->setDataArr(dataArr);

             m_channelData[col*rows+row]=tmpHeartData;

         }
     }
 }

 void ECGTestDialog::drawECGGrid(QPainter &painter,int width,int height,double){
     painter.save();
     painter.setPen(QColor(247,250,250));
     for(int i=0;i<width/DOTS;i++){
         painter.drawLine(0,i*DOTS,width,i*DOTS);
         painter.drawLine(i*DOTS,0,i*DOTS,height);
     }

     painter.setPen(QColor(206,224,229));
     for(int i=0;i<width/DOTS/5;i++){
         painter.drawLine(0,i*DOTS*5,width,i*DOTS*5);
         painter.drawLine(i*DOTS*5,0,i*DOTS*5,height);
     }
     painter.restore();
 }
 int p=0;
  void ECGTestDialog::updateECGWave(QPainter &painter, int width, int height, double dots)
  {
      QPixmap*pixmap=new QPixmap(this->size());
      pixmap->fill(Qt::white);
      painter.drawPixmap(0,0,*pixmap,0,0,0,0);
      drawECGGrid(painter,width,height,dots);

      for(int i=0;i<12;i++)
      {
          QString data=QString::fromLocal8Bit(m_newdata.at(i));
          m_channelData[i]->addData(data.toInt());
      }
      painter.save();
      float fpPerMv=10*dots;
      float fpPerUv=0.001*fpPerMv;//每uv像素
      int rectWidth=width/2;
      int rowHeight=height/6;
      int middleHeight=rowHeight/2;
      int cols=2;
      int rows=6;
      for(int col=0;col<cols;col++)
      {
          for(int row=0;row<rows;row++)
          {
              QString channelName=m_channelData[col*rows+row]->getChannelName();
              QJsonArray dataAtrr=m_channelData[col*rows+row]->getDataArr();
              int wavelength=dataAtrr.size();
              QVector<QPointF>vecPoints;
              for(int i=0;i<wavelength;i++)
              {
                  if(i>rectWidth-dots)
                  {
                      break;
                  }
                  QPointF p(rectWidth*col+i,row*rowHeight+middleHeight-dataAtrr[i].toInt()*fpPerUv+25);
                  qDebug()<<rectWidth*col+i<<","<<row*rowHeight+middleHeight-dataAtrr[i].toInt()*fpPerUv+25;
                  vecPoints.append(p);
              }
              painter.save();
              painter.setPen(QColor(62,168,115));
              painter.drawText(col*rectWidth,row*rowHeight+middleHeight+25,channelName);
 //             qDebug()<<channelName;
              painter.restore();
              for(int i=0;i<vecPoints.size()-1;i++)
              {
                  painter.drawLine(vecPoints[i],vecPoints[i+1]);
              }

          }
      }
      painter.restore();
  }

 void ECGTestDialog::drawHisECGWave(QPainter &painter, int width, int height, double dots){
     drawECGGrid(painter,width,height,DOTS);
     painter.save();
     float fpPerMv=10*DOTS;
     float fpPerUv= fpPerMv/1000;

     int rectWidth =width/2;
     int rowHeight =height/6;
     int middleHeight=rowHeight/2;
     int cols=2;
     int rows=6;
     for(int col=0;col<cols;col++){
         for(int row=0;row<rows;row++){
             int wavelen= m_channelData[col*rows+row]->getDataArr().size();
             QVector<QPoint> vecPoints;
             QString name=m_channelData[col*rows+row]->getChannelName();
             QJsonArray data=m_channelData[col*rows+row]->getDataArr();
             for(int i=0;i<wavelen;i++){
                 if(i>rectWidth-dots*2)
                     break;
                 QPoint p((qreal)(col*rectWidth+i),(qreal)(row*rowHeight+middleHeight-data[i].toInt()*fpPerUv)+25);
                 vecPoints.append(p);
             }
             painter.save();
             painter.setPen(QColor(62,168,115));
             painter.drawText(col*rectWidth,row*rowHeight+middleHeight+25,name);
             painter.restore();


             for(int i=0;i<vecPoints.size()-1;i++){
                 painter.drawLine(vecPoints[i],vecPoints[i+1]);
             }
         }
     }


     painter.restore();
 }
void ECGTestDialog::receiveData()
 {
    QByteArray message=m_serial->m_serialport->readAll();
    m_newdata=message.split(',');//分解数据
    m_serialflag=true;
    repaint();
 }
 bool ECGTestDialog::serialPortInit()
 {
     m_serial=new SerialTool();
     m_serial->m_serialport=new QSerialPort();
     connect(m_serial->m_serialport,SIGNAL(readyRead()),this,SLOT(receiveData()));
     if(m_serial->serialOpen())
     {
         return true;
     }
     else
     {
         return false;
     }
 }

void ECGTestDialog::on_backButton_clicked()
{
    m_serial->serialClose();
    close();
}
